package edu.gdit.health.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;

import edu.gdit.health.config.MD5;
import edu.gdit.health.model.SysUser;
import edu.gdit.health.service.SysUserService;


@Controller
@RequestMapping("api")
public class ApiController {
	private static final Log log = LogFactory.getLog(ApiController.class);
	@Autowired
	private SysUserService sysUserService;
	@RequestMapping("getPage")
	public String  getPage(String pageName) {
		log.warn(String.format("用户打开了新页面[%s]。", pageName));
		return pageName==null?"index":pageName;
	}
	@RequestMapping(value = {"/login"}, method = RequestMethod.GET)
	public String loginIndex() {
	    return "login";
	}

	@RequestMapping(value = {"/login"}, method = RequestMethod.POST)
	public String login(@RequestParam(name = "username")String username, @RequestParam(name = "password")String password,
	                    Model model, HttpServletRequest request) {
	    SysUser user = sysUserService.getPwd(username);
	    String pwd="";
	    //pwd是数据库里的密码
	    if(user!=null){
	        pwd = user.getPassword();}
	    else {
	        return "login";
	    }
	    //password1是用户输入的密码
	    String password1 = MD5.crypt(password);
	    //判断二者是否相等
	    if (pwd.equals(password1)) {
	        model.addAttribute("user", user);
	        request.getSession().setAttribute("user", user);
	        return "index";
	    } else {
	        return "login";
	    }
	}
	@RequestMapping(value = {"/logout"}, method = RequestMethod.GET)
	public String logOut(HttpSession session) {
		session.removeAttribute("user");
	    return "login";
	}
}
